﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace XrmLibrary.MsCrm4Adapter.Extensions
{
    public static class FilterExpressionExtensions
    {
        public static Microsoft.Crm.Sdk.Query.FilterExpression ToCrm4FilterExpression(this Microsoft.Xrm.Sdk.Query.FilterExpression crm2011FilterExpression)
        {
            Microsoft.Crm.Sdk.Query.FilterExpression crm4FilterExpression =
                new Microsoft.Crm.Sdk.Query.FilterExpression();

            // Set the Logical Operator.
            crm4FilterExpression.FilterOperator = crm2011FilterExpression.FilterOperator.ToCrm4LogicalOperator();

            // Add the ConditionExpression objects.
            foreach (Microsoft.Xrm.Sdk.Query.ConditionExpression conditionExpression in crm2011FilterExpression.Conditions)
            {
                crm4FilterExpression.AddCondition(conditionExpression.ToCrm4ConditionExpression());
            }

            // Set the Child Filters (if any).
            foreach (Microsoft.Xrm.Sdk.Query.FilterExpression filterExpression in crm2011FilterExpression.Filters)
            {
                crm4FilterExpression.Filters.Add(filterExpression.ToCrm4FilterExpression());
            }

            return crm4FilterExpression;
        }

        public static Microsoft.Xrm.Sdk.Query.FilterExpression ToCrm2011FilterExpression(this Microsoft.Crm.Sdk.Query.FilterExpression crm4FilterExpression)
        {
            Microsoft.Xrm.Sdk.Query.FilterExpression crm2011FilterExpression = new Microsoft.Xrm.Sdk.Query.FilterExpression();

            // Set the Logical Operator.
            crm2011FilterExpression.FilterOperator = crm4FilterExpression.FilterOperator.ToCrm2011LogicalOperator();

            // Set the Conditions.
            crm2011FilterExpression.Conditions.AddRange(crm4FilterExpression.Conditions.ToCrm2011ConditionExpressionCollection());

            // Set Child Filters (if any).
            crm2011FilterExpression.Filters.AddRange(crm4FilterExpression.Filters.ToCrm2011FilterExpressionCollection());

            return crm2011FilterExpression;
        }

        public static IEnumerable<Microsoft.Xrm.Sdk.Query.FilterExpression> ToCrm2011FilterExpressionCollection(this ArrayList crm4FilterExpression)
        {
            foreach (Microsoft.Crm.Sdk.Query.FilterExpression filterExpression in crm4FilterExpression)
            {
                yield return filterExpression.ToCrm2011FilterExpression();
            }
        }
    }
}
